import React, { FC, useEffect, useState } from 'react'
import { SearchBar, Result, Tag, Divider, List, Empty } from 'antd-mobile'
import { SmileOutline, LikeOutline, EditSOutline, HeartOutline, UserOutline, EnvironmentOutline, ClockCircleOutline, FireFill } from 'antd-mobile-icons'
import dayjs from 'dayjs'

import { getalltravelsAPI } from '../../api/api'
import MyHeader from '../../components/MyHeader'
import { baseURL } from '../../api/request'
import './Search.scss'
import { ShowMsg } from '../../utils/message'
import { useLocalStorageState } from 'ahooks'
import { useNavigate } from 'react-router-dom'


const Search: FC = () => {
  const router = useNavigate()
  const [flag, setFlag] = useState<boolean>(false)
  const [list, setList] = useState<any>([])
  const [searchList, setSearchList] = useState<any>([])
  const [searchTag, setSearchTag] = useState<string>('')


  const [searchHistoryList, setSearchHistoryList] = useLocalStorageState<any>(
    'searchHistoryList',
    {
      defaultValue: []
    }
  )

  const getSearchList = async () => {
    const res: any = await getalltravelsAPI()
    if (res.code == 200) {
      setList(res.result)
      setSearchList(res.result)
    }
  }

  useEffect(() => {
    getSearchList()
  }, [])

  // 开始搜索
  const onSearch = (value: any) => {
    setFlag(true)
    console.log(value);
    const res = list.filter((item: any) => {
      return item.tags.some((v: any) => {
        return v.label === value
      })
    })
    setSearchList(res)
    setSearchTag(value)
    // 将搜索关键词添加到历史记录
    searchHistoryList.unshift(value)
    // searchHistoryList.unshift(value)
    setSearchHistoryList(Array.from(new Set(searchHistoryList)))
    if (searchList.length == 0) {
      ShowMsg("没有搜索到相关内容")
    }
  }


  // 取消搜索
  const onCancel = () => {
    setFlag(false)
  }


  return (
    <div>
      <MyHeader title='搜 索'></MyHeader>
      <div style={{ padding: '5px' }}>
        <SearchBar
          placeholder='请输入搜索关键词'
          showCancelButton
          onSearch={onSearch}
          onCancel={onCancel} />
      </div>
      {
        flag ?
          <div className='class-content'>
            {
              searchList.map((item: any) => {
                return (
                  <div key={item._id} className='class-content-box' onClick={() => router('/detail/' + item._id + '?title=' + item.title)}>
                    <p className='content-title'>{item.title}</p>
                    <p className='content-username'>
                      <UserOutline />：
                      {item.author?.username}
                    </p>
                    <p className='content-address'>
                      <EnvironmentOutline />：
                      {item.address}
                    </p>
                    <p className='content-date'>
                      <ClockCircleOutline />：
                      {dayjs(item.date).format("YYYY-MM-DD")}
                    </p>
                    <p className='content-hot'>
                      <FireFill />：
                      热度：{item.hot}
                    </p>
                    {
                      item.tags.map((v: any, n: any) => {
                        return (
                          <Tag color={v.label == searchTag ? '#ff6430' : 'success'} key={n} className="content-tag">{v.label}</Tag>
                        )
                      })
                    }
                    <div className='content-imgbox'>
                      {
                        item.imgs.map((e: any, i: any) => {
                          return (
                            <img src={e.url?.replace(/public/, baseURL)} alt='' key={i} />
                          )
                        })
                      }
                    </div>
                    <p className='content-content'>{item.content}</p>
                    <div className='content-footer'>
                      <span><LikeOutline />：0</span>
                      <span><EditSOutline />：0</span>
                      <span><HeartOutline />：0</span>
                    </div>
                  </div>
                )
              })
            }
          </div>
          :
          <div>
            <Result
              icon={<SmileOutline />}
              status='success'
              title='在输入框输入内容以开始搜索'
              description='建议输入关键词为标题或标签 如：露营，户外，滑雪'
            />
          </div>
      }

      <Divider
        style={{
          color: '#1677ff',
          borderColor: '#1677ff',
          borderStyle: 'dashed',
          padding: '0 15px'
        }}
      >
        搜索历史
      </Divider>

      {
        searchHistoryList.length > 0 ?
          <List style={{ padding: '0 5px' }}>
            {
              searchHistoryList.map((item: any, index: any) => {
                return (
                  <List.Item key={index} onClick={() => { }}>{item}</List.Item>
                )
              })
            }
          </List>
          :
          <div>
            <Empty
              style={{ padding: '64px 0' }}
              imageStyle={{ width: 128 }}
              description='暂无数据'
            />
          </div>
      }
    </div>
  )
}

export default Search
